// Copyright 2020 newtbig Author. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server

import (
	"errors"
	"fmt"
	"net"

	"gitee.com/lakertt/newtbig/gate/connect/tcp"
	"gitee.com/lakertt/newtbig/gate/session"
	log "gitee.com/lakertt/newtbig/logging"
)

func (s *Server) run_tcp() error {
	lis, err := net.Listen("tcp", ":"+s.Port)
	if err != nil {
		return err
	}
	defer lis.Close()
	s.setListener(lis)
	log.Logger.Info("tcp listening on: ", lis.Addr())
	for {
		conn, err := lis.Accept()
		if err != nil {
			//Go 1.16+
			if errors.Is(err, net.ErrClosed) {
				return fmt.Errorf("listener closed err: %s", err.Error())
			}
			log.Logger.Errorf("tcp accept err:", err.Error())
			continue
		}
		if session.GetSessionMgr().Count() > s.opts.MaxConn {
			log.Logger.Warn("tcp connect too much err  ip:", conn.RemoteAddr())
			conn.Close()
			continue
		}

		connect, errC := tcp.NewConnect(conn, s.opts)
		if errC != nil || connect == nil {
			log.Logger.Error("tcp connect init err ! ", errC.Error())
			conn.Close()
			continue
		}

		ss := session.NewSession(s.getApp())
		if ss != nil {
			err := ss.OnStart(connect)
			if err != nil {
				ss.OnStop()
			}
		}
	}
}
